import React, { useContext, useState } from "react"
import { places, Places } from './data'
import { ImageSizeContext } from "./Context"


export default function ImageApp() {
    const [isLarge, setIsLarge] = useState(false)
    const imageSize = isLarge ? 150 : 100

    return (
        <ImageSizeContext.Provider value={imageSize}>
            <label >
                <input
                    type="checkbox"
                    checked={isLarge}
                    onChange={e => setIsLarge(e.target.checked)}
                />
                Use large images
            </label>
            <hr />
            <List />
        </ImageSizeContext.Provider>
    )
}

function List() {
    const ulStyle: React.CSSProperties = {
        listStyleType: 'none',
        margin: 0,
    };
    const listItems: React.ReactNode[] = places.map(item => (
        <li key={item.id}>
            <PlaceImage place={item} />
        </li>
    ))
    return <ul style={ulStyle}>{listItems}</ul>
}


function PlaceImage({ place }: { place: Places }) {
    const divStyle: React.CSSProperties = {
        display: 'flex',
        flexDirection: 'row' as const
    }

    return (
        <div style={divStyle}>
            <Card place={place} />
            <p>
                <b>{place.name}</b>
                {': ' + place.description}
            </p>
        </div>
    )
}

function Card({ place }: { place: Places }) {
    const imageSize: number = useContext(ImageSizeContext)
    return (
        <img
            src={getImageUrl(place)}
            alt={place.name}
            width={imageSize}
            height={imageSize}
        />
    )
}

function getImageUrl(place: Places) {
    return (
        'https://i.imgur.com/' +
        place.imageId +
        'l.jpg'
    );
}
